package com.XDApp.xdbase.fragment;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.XDApp.xdbase.BaseApplication;
import com.XDApp.xdbase.XDHttpClient;
import com.XDApp.xdbase.activitys.LoginActivity;
import com.XDApp.xdbase.activitys.MainActivity;
import com.XDApp.xdbase.activitys.MyAddressActivity;
import com.XDApp.xdbase.activitys.MyCommentActivity;
import com.XDApp.xdbase.activitys.MyContactActivity;
import com.XDApp.xdbase.activitys.MyFavoriteActivity;
import com.XDApp.xdbase.activitys.MySettingActivity;
import com.XDApp.xdbase.bean.User;
import com.XDApp.xdbase.utils.ACache;
import com.XDApp.xdbase.utils.CommonUtil;
import com.XDApp.xdbase.utils.ProgressHUD;
import com.XDApp.xdbase.utils.UpdateUserState;
import com.XDApp.xdbase.utils.xdConfig;
import com.XDApp.xdbase.utils.UpdateUserState.IUpdateUserState;
import com.XDApp.xdbase.view.CRToast;
import com.XDApp.xdbase.view.CircleImageView;
import com.XDApp.xdbase.xinsilu.R;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.squareup.picasso.Picasso;

public class MyFragment extends XDBaseFragment implements OnClickListener {

	private static final String TAG = "MyFragment";
	private View inflate;
	private RelativeLayout rl_login, rl_login_out, rl_myfavorite, rl_mycomment, rl_mycontact, rl_myaddress;
	private BaseApplication mApplication;
	private TextView tv_right, tv_title;
	private TextView login;
	private ImageView iv_back;
	private TextView tv_setting;
	private TextView tv_username;
	private CircleImageView iv_headicon;
	private User user;

	private SharedPreferences sp;
	private String nickName;
	private String userID;
	private String pwd;
	private String userLogo;

	private ACache mCache;
	private boolean isChange = false;
	private Bitmap asBitmap;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		inflate = inflater.inflate(R.layout.fragment_my, container, false);
		mApplication = BaseApplication.getApplication();
		return inflate;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		mCache = ACache.get(mContext);
		user = new User();
		sp = mContext.getSharedPreferences(MainActivity.class.getSimpleName(), mContext.MODE_PRIVATE);
		rl_login = (RelativeLayout) inflate.findViewById(R.id.rl_login);
		rl_login_out = (RelativeLayout) inflate.findViewById(R.id.rl_login_out);
		tv_setting = (TextView) inflate.findViewById(R.id.tv_person_set);

		rl_myfavorite = (RelativeLayout) inflate.findViewById(R.id.rl_myfavorite);
		rl_mycomment = (RelativeLayout) inflate.findViewById(R.id.rl_mycomment);
		rl_mycontact = (RelativeLayout) inflate.findViewById(R.id.rl_mycontact);
		rl_myaddress = (RelativeLayout) inflate.findViewById(R.id.rl_myaddress);

		tv_right = (TextView) inflate.findViewById(R.id.title_right);
		tv_title = (TextView) inflate.findViewById(R.id.title_text);
		iv_back = (ImageView) inflate.findViewById(R.id.title_back);
		tv_username = (TextView) inflate.findViewById(R.id.tv_username);
		iv_headicon = (CircleImageView) inflate.findViewById(R.id.iv_headicon);

		login = (TextView) inflate.findViewById(R.id.login);

		rl_myfavorite.setOnClickListener(this);
		rl_mycomment.setOnClickListener(this);
		rl_mycontact.setOnClickListener(this);
		rl_myaddress.setOnClickListener(this);
		login.setOnClickListener(this);

		tv_setting.setOnClickListener(this);
		tv_right.setOnClickListener(this);
		initData();
		UpdateUserState.add(iUpdateUserState);
	}

	IUpdateUserState iUpdateUserState = new IUpdateUserState() {

		@Override
		public void update(Intent data) {
			if (data == null) {
				mCache.put("xslBitmap", "");
				mApplication.setLogin(false);
				Editor editor = sp.edit();
				editor.putString("phone", "").commit();
				editor.putString("pwd", "").commit();
				editor.putString("userLogo", "").commit();
				editor.putString("nickName", "").commit();
				editor.putString("userID", "").commit();
				editor.putBoolean("isChange", false).commit();
				rl_login.setVisibility(View.GONE);
				rl_login_out.setVisibility(View.VISIBLE);
				tv_right.setText("");
			} else {
				boolean loginSuccess = data.getBooleanExtra("loginSuccess", false);
				nickName = data.getStringExtra("nickName");
				userID = data.getStringExtra("userID");
				pwd = data.getStringExtra("pwd");
				userLogo = data.getStringExtra("userLogo");
				if (loginSuccess) {
					rl_login.setVisibility(View.VISIBLE);
					rl_login_out.setVisibility(View.GONE);
					tv_right.setText("注销");
					tv_right.setTextColor(Color.WHITE);
					tv_username.setText(nickName);

					if (isChange) {
						if (asBitmap == null) {
							iv_headicon.setBackgroundResource(R.drawable.set_headicon);
						} else {
							iv_headicon.setImageBitmap(asBitmap);
						}
					} else {
						if (TextUtils.isEmpty(userLogo)) {
							iv_headicon.setBackgroundResource(R.drawable.set_headicon);
						} else {
							Picasso.with(mContext).load(userLogo).placeholder(R.drawable.set_headicon)
									.into(iv_headicon);
						}
					}
				}
			}
		}
	};

	@Override
	public void onDestroy() {
		super.onDestroy();
		UpdateUserState.remove(iUpdateUserState);
	}

	private void initData() {
		isChange = sp.getBoolean("isChange", false);
		if (mApplication.isLogin()) {
			user = mApplication.getUser();
			nickName = user.getNickName();
			userID = user.getUserID();
			pwd = user.getPwd();
			userLogo = user.getUserLogo();
			rl_login.setVisibility(View.VISIBLE);
			rl_login_out.setVisibility(View.GONE);
			tv_right.setText("注销");
			tv_right.setTextColor(Color.WHITE);
			tv_username.setText(nickName);
			if (isChange) {
				asBitmap = mCache.getAsBitmap("xslBitmap");
				if (asBitmap == null) {
					iv_headicon.setBackgroundResource(R.drawable.set_headicon);
				} else {
					iv_headicon.setImageBitmap(asBitmap);
				}
			} else {
				if (TextUtils.isEmpty(userLogo)) {
					iv_headicon.setBackgroundResource(R.drawable.set_headicon);
				} else {
					Picasso.with(mContext).load(userLogo).placeholder(R.drawable.set_headicon)
							.into(iv_headicon);
//					ImageLoader.getInstance().displayImage(userLogo, iv_headicon);
				}
			}

		} else {
			rl_login.setVisibility(View.GONE);
			rl_login_out.setVisibility(View.VISIBLE);
			tv_right.setText("");
		}
		iv_back.setVisibility(View.GONE);
		tv_title.setText("我的新丝路");
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (null == data) {
			return;
		}

		if (requestCode == 100) {
			boolean loginSuccess = data.getBooleanExtra("loginSuccess", false);
			nickName = data.getStringExtra("nickName");
			userID = data.getStringExtra("userID");
			pwd = data.getStringExtra("pwd");
			userLogo = data.getStringExtra("userLogo");
			if (loginSuccess) {
				rl_login.setVisibility(View.VISIBLE);
				rl_login_out.setVisibility(View.GONE);
				tv_right.setText("注销");
				tv_right.setTextColor(Color.WHITE);
				tv_username.setText(nickName);

				if (isChange) {
					if (asBitmap == null) {
						iv_headicon.setBackgroundResource(R.drawable.set_headicon);
					} else {
						iv_headicon.setImageBitmap(asBitmap);
					}
				} else {
					if (TextUtils.isEmpty(userLogo)) {
						iv_headicon.setBackgroundResource(R.drawable.set_headicon);
					} else {
						Picasso.with(mContext).load(userLogo).placeholder(R.drawable.set_headicon)
								.into(iv_headicon);
					}
				}
			}
		}
		if (requestCode == 101) {
			nickName = data.getStringExtra("nickName");
			userLogo = data.getStringExtra("userLogo");
			tv_username.setText(nickName);

			asBitmap = mCache.getAsBitmap("xslBitmap");

			if (asBitmap == null) {
				iv_headicon.setBackgroundResource(R.drawable.set_headicon);
			} else {
				iv_headicon.setImageBitmap(asBitmap);
			}
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.rl_myfavorite:// 我的收藏
			if (mApplication.isLogin()) {
				Intent intent1 = new Intent(mContext, MyFavoriteActivity.class);
				startActivity(intent1);
			} else {
				Intent intent1 = new Intent(mContext, LoginActivity.class);
				startActivityForResult(intent1, 100);
			}
			break;
		case R.id.rl_mycomment:// 我的点评
			if (mApplication.isLogin()) {
				Intent intent1 = new Intent(mContext, MyCommentActivity.class);
				startActivity(intent1);
			} else {
				Intent intent1 = new Intent(mContext, LoginActivity.class);
				startActivityForResult(intent1, 100);
			}
			break;
		case R.id.rl_mycontact:// 常用联系人
			if (mApplication.isLogin()) {
				Intent intent3 = new Intent(mContext, MyContactActivity.class);
				startActivity(intent3);
			} else {
				Intent intent1 = new Intent(mContext, LoginActivity.class);
				startActivityForResult(intent1, 100);
			}
			break;
		case R.id.rl_myaddress:// 常用邮寄地址
			if (mApplication.isLogin()) {
				Intent intent4 = new Intent(mContext, MyAddressActivity.class);
				startActivity(intent4);
			} else {
				Intent intent1 = new Intent(mContext, LoginActivity.class);
				startActivityForResult(intent1, 100);
			}
			break;
		case R.id.tv_person_set:// 点击进入个人设置中心
			Intent intent5 = new Intent(mContext, MySettingActivity.class);
			intent5.putExtra("phone", sp.getString("phone", ""));
			intent5.putExtra("nickName", nickName);
			intent5.putExtra("pwd", pwd);
			intent5.putExtra("userID", userID);
			intent5.putExtra("userLogo", userLogo);
			startActivityForResult(intent5, 101);
			break;
		case R.id.title_right:// 注销
			getData();
			break;
		case R.id.login:// 登录
			Intent intent6 = new Intent(mContext, LoginActivity.class);
			startActivityForResult(intent6, 100);
			break;
		default:
			break;
		}
	}

	// TODO 访问网络获取数据
	private void getData() {
		if (CommonUtil.checkNetState(mContext)) {
			RequestParams params = new RequestParams();
			params.put("userID", userID);
			params.put("ostype", xdConfig.ANDRODID);

			final ProgressHUD ProgressDialog = ProgressHUD.show(mContext, "正在加载...", true, true, null);
			XDHttpClient.post(xdConfig.LOGOUT, params, new AsyncHttpResponseHandler() {
				@Override
				public void onSuccess(int statusCode, String content) {
					Log.e(TAG, content);
					if (null != ProgressDialog && ProgressDialog.isShowing())
						ProgressDialog.dismiss();
					if (content.startsWith("{")) {
						return;
					}

					JSONObject obj = JSONObject.parseObject(content);
					String state = obj.getString("state");
					if ("1".equals(state)) {
						CRToast.show(mContext, "注销成功");
						mCache.put("xslBitmap", "");
						mApplication.setLogin(false);
						Editor editor = sp.edit();
						editor.putString("phone", "").commit();
						editor.putString("pwd", "").commit();
						editor.putString("userLogo", "").commit();
						editor.putString("nickName", "").commit();
						editor.putString("userID", "").commit();
						editor.putBoolean("isChange", false).commit();
						rl_login.setVisibility(View.GONE);
						rl_login_out.setVisibility(View.VISIBLE);
						tv_right.setText("");
					} else {

					}
				}

				@Override
				public void onFailure(Throwable arg0, String arg1) {
					if (null != ProgressDialog && ProgressDialog.isShowing()) {
						ProgressDialog.dismiss();
					}
					super.onFailure(arg0, arg1);
					Toast.makeText(mContext, R.string.pLease_check_network, 0).show();
				}
			});
		} else {
			Toast.makeText(mContext, R.string.pLease_check_network, 0).show();
		}
	}
}
